<template>
  <!-- 维修附加项 -->
  <el-dialog
    v-model="props.visible"
    width="800px"
    :show-close="false"
    :close-on-click-modal="false"
    :before-close="handleClose"
  >
    <template #header="{ close, titleId, titleClass }">
      <div class="my-header">
        <h4
          :id="titleId"
          :class="titleClass"
        >
          <!-- 维修附加项 -->
          {{ t('dockRepair.AdditionItem.title') }}
        </h4>
        <img
          src="@/assets/img/icon_guanbi.png"
          @click="close"
          class="close"
        />
      </div>
    </template>

    <el-tree-v2
      v-if="defaultExpandedKeys.length"
      ref="treeV2"
      :data="data"
      :props="propsTree"
      :default-expanded-keys="defaultExpandedKeys"
      show-checkbox
      :height="500"
      @check="handleCheck"
    />

    <template #footer>
      <div class="dialog-footer flexcc">
        <el-button
          color="#252628"
          plain
          @click="cancel"
        >
          {{ t('cancelText') }}
        </el-button>
        <el-button
          type="primary"
          color="#252628"
          @click="confirm"
          :disabled="isConfirmDisabled"
        >
          {{ t('confirmText') }}
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { computed, onBeforeMount, ref } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { useI18n } from 'vue-i18n'
import { getRepairAddTreeApi } from '@/service/dockOrder'

const { t, locale } = useI18n()

const router = useRouter()
const route = useRoute()

onBeforeMount(() => {
  getData()
})

const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  }
})

const emit = defineEmits(['close', 'confirm'])

const handleClose = () => {
  emit('close')
}

const cancel = () => {
  handleClose()
}
const confirm = () => {
  const checkedData = treeV2.value.getCheckedNodes()
  // console.log(checkedData, '==')
  emit('confirm', checkedData[0])
  handleClose()
}

// 禁用确认按钮
const isConfirmDisabled = computed(() => {
  return !treeV2.value?.getCheckedNodes().length
})

// ref
const treeV2 = ref(null)

//获取数据
const data = ref([])
const defaultExpandedKeys = ref([])
const getData = () => {
  getRepairAddTreeApi().then(({ data: d }) => {
    data.value = d
    defaultExpandedKeys.value = d.map((item) => item.id)
    setDisabled()
  })
}

// 只能选 最后一级
const setDisabled = () => {
  const fn = (arr) => {
    arr.forEach((item) => {
      if (item.repairAddList.length) {
        item.disabled = true
      }
      fn(item.repairAddList)
    })
  }
  fn(data.value)
}

// 树形 props
const propsTree = {
  value: 'id',
  label: 'projectName',
  children: 'repairAddList',
  disabled: 'disabled'
}

// 当复选框被点击的时候触发
const handleCheck = (data, info) => {
  // console.log(data, info)
  treeV2.value.setCheckedKeys([data.id]) // 单选
}
</script>

<style scoped lang="scss"></style>
